package com.cszy.yydqbfq.base

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.event.SingleLiveEvent
import com.cszy.yydqbfq.utils.SpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans

import com.hnyyaa.wifiwnmyfhq3by.ui.base.IViewModel
import com.lzx.starrysky.SongInfo


import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), IViewModel, DefaultLifecycleObserver {

    val ui: UIChange by lazy { UIChange() }

    /**
     * 网络请求在viewModelScope域中启动，页面销毁时会调用onCleared方法取消所有协程
     */
    fun launch(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch() { block() }

    /**
     * UI事件
     */
    inner class UIChange {
        val showDialog by lazy { SingleLiveEvent<String>() }
        val dismissDialog by lazy { SingleLiveEvent<Void>() }
        val toast by lazy { SingleLiveEvent<String>() }
        val msgEvent by lazy { SingleLiveEvent<BaseEvent>() }
    }

    override fun showLoading(text: String) {
        ui.showDialog.postValue(text)
    }

    override fun dismissLoading() {
        ui.dismissDialog.call()
    }

    override fun toast(text: String) {
        ui.toast.postValue(text)
    }

    override fun handleEvent(event: BaseEvent) {
        ui.msgEvent.postValue(event)
    }


    //本地获取的音乐转成后台获取的MusicListBean
    fun convertToMusicListBeanList(audioItemList: List<AudioItemBean>): List<MusicListBean> {
        return audioItemList.mapIndexed { index, audioItem ->
            MusicListBean().apply {
                id = index// Using the actual ID from AudioItemBean
                name = audioItem.title
                author = audioItem.artist
                imageUrl = "" // AudioItemBean doesn't have imageUrl, so we set empty
                songUrl = audioItem.path
                category = "本地音乐" // You might want to set this based on your requirements

            }
        }
    }


    //网络获取的音乐转songInfo
    fun convertToSongInfoList(musicList: List<MusicListBean>): List<SongInfo> {
        var  app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        val songInfoList = musicList.mapIndexed { index, musicBean ->
            SongInfo().apply {
                songId = index.toString() // 使用下标作为ID
                songUrl = musicBean.songUrl ?: ""
                songName = if (app_process=="0"){musicBean.alias?: ""}else{musicBean.name ?: ""}
                artist = musicBean.author ?: ""
                songCover = musicBean.imageUrl ?: ""
                // 其他字段根据需要设置默认值
                duration = -1
                decode = false
            }
        }
        return songInfoList
    }

}